package com.carqueue.controller;

import com.carqueue.utils.AmapUtils;
import lombok.val;
import org.json.JSONException;
import org.json.JSONObject;
import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carqueue.CarQueueApplication;
import com.carqueue.common.Result;
import com.carqueue.dto.CaaQueueDtomap;
import com.carqueue.dto.CarQueueDto;
import com.carqueue.pojo.CarQueue;
import com.carqueue.pojo.User;
import com.carqueue.service.CarQueueService;
import com.carqueue.service.UserService;
import com.carqueue.utils.InvitationCodeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;




@RestController
@RequestMapping
public class CarQueueController {
    @Autowired
    private CarQueueService carQueueService;

    @Autowired
    private UserService userService;
    String ak = "VfiOIuOVnGszPlzTQCUGtMxo9GDpZjD2";
    /**
     * 创建车队
     * @param map
     * @return
     */
    @PostMapping("/create")
    @Transactional
    public Result<String> create(@RequestBody Map map){
        String startpoint = map.get("startpoint").toString();
        String endpoint = map.get("endpoint").toString();
        int fleetspacing =Integer.valueOf(map.get("fleetspacing").toString()); /*(int) map.get("fleetspacing");*/
        int fleetspeed = Integer.valueOf(map.get("fleetspeed").toString()); /*(int) map.get("fleetspeed");*/
        String username = map.get("username").toString();
        CarQueue carQueue = new CarQueue();

        /**
         * 此处需要修改为 调用生成邀请码方法
         * *已修改
         */
//        String invitationcode=new String("temp");
        String invitationcode= InvitationCodeUtils.randomInvitationCode();

        carQueue.setStartpoint(startpoint);
        carQueue.setEndpoint(endpoint);
        carQueue.setFleetspacing(fleetspacing);
        carQueue.setFleetspeed(fleetspeed);
        carQueue.setLeader(username);
        carQueue.setTailer(username);
        carQueue.setInvitationcode(invitationcode);
        carQueue.setNumofcar(1);

        carQueueService.save(carQueue);

        /**
         * 修改用户表，更新用户的invitationcode
         */
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,username);
        User user = userService.getOne(lambdaQueryWrapper);
        user.setInvitationcode(invitationcode);
//        user.setPrecar(username);
        userService.updateById(user);

        return Result.success("创建车队成功");
    }

    @PostMapping("/join")
    public Result<String> join(@RequestBody Map map){
        return carQueueService.join(map);
    }


    /**
     * 退出车队
     * @param
     * @return
     */
    @PostMapping("/quit")
    @Transactional
    public Result<String> quit(@RequestBody User user1){
        String username= user1.getUsername();
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User user = userService.getOne(queryWrapper);

        String invitationcode = user.getInvitationcode();
        LambdaQueryWrapper<CarQueue> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CarQueue::getInvitationcode, invitationcode);
        CarQueue carQueue = carQueueService.getOne(lambdaQueryWrapper);

        if(carQueue.getNumofcar()==1){
            carQueueService.removeById(carQueue);
            user.setInvitationcode(null);
            user.setPrecar(null);
            userService.updateById(user);
            return Result.success("退出车队成功");
        }else if(carQueue.getLeader().equals(username)){
            LambdaQueryWrapper<User> userLambdaQueryWrapper=new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPrecar,username);
            User newLeader = userService.getOne(userLambdaQueryWrapper);

            user.setInvitationcode(null);
            user.setPrecar(null);
            //userService.updateById(user);
            List<User> list=new ArrayList<>();
            list.add(user);

            newLeader.setPrecar(null);
            list.add(newLeader);
            userService.updateBatchById(list);

            carQueue.setLeader(newLeader.getUsername());
            carQueue.setNumofcar(carQueue.getNumofcar()-1);
            carQueueService.updateById(carQueue);
            return Result.success("退出车队成功");
        }else if(carQueue.getTailer().equals(username)){
            String newTailer = user.getPrecar();

            user.setInvitationcode(null);
            user.setPrecar(null);
            userService.updateById(user);

            carQueue.setTailer(newTailer);
            carQueue.setNumofcar(carQueue.getNumofcar()-1);
            carQueueService.updateById(carQueue);
            return Result.success("退出车队成功");
        }else {
            String preCar = user.getPrecar();
            user.setInvitationcode(null);
            user.setPrecar(null);
            List<User> list=new ArrayList<>();
            list.add(user);

            LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(User::getPrecar,username);
            User nextCar = userService.getOne(wrapper);

            nextCar.setPrecar(preCar);
            //userService.updateById(nextCar);
            list.add(nextCar);
            userService.updateBatchById(list);

            carQueue.setNumofcar(carQueue.getNumofcar()-1);
            carQueueService.updateById(carQueue);
            return Result.success("退出车队成功");
        }
    }

    /**
     * 车队数据查询
     *
     */
    @GetMapping("/show1")
    public Result<Page> show(int page,int pagesize,String invitationcode){
        Page<User> userPage=new Page<>(page,pagesize);
        Page<CarQueueDto> dtoPage=new Page<>(page,pagesize);
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getInvitationcode,invitationcode);
        userService.page(userPage,lambdaQueryWrapper);


        LambdaQueryWrapper<CarQueue> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(CarQueue::getInvitationcode,invitationcode);
        CarQueue carQueue = carQueueService.getOne(queryWrapper);

        BeanUtils.copyProperties(userPage,dtoPage);

        List<CarQueueDto> records = dtoPage.getRecords();
        records=records.stream().map(item->{
            BeanUtils.copyProperties(carQueue,item);
            return item;
        }).collect(Collectors.toList());
        dtoPage.setRecords(records);
        return Result.success(dtoPage);
    }

    /**
     *管理员界面，查看所有车队
     */
    @GetMapping("/showfleet")
    public Result<Page> showfleet(int page,int pagesize){
        Page<CarQueue> carQueuePage=new Page<>(page,pagesize);
        carQueueService.page(carQueuePage);
        return Result.success(carQueuePage);
    }

    @PostMapping("/map")
    @Transactional
    public Result<List<CaaQueueDtomap>> map(@RequestBody User user) throws JSONException {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        User one = userService.getOne(queryWrapper);

        LambdaQueryWrapper<CarQueue> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(CarQueue::getInvitationcode,one.getInvitationcode());
        CarQueue one1 = carQueueService.getOne(queryWrapper1);
        if(one1==null)
        {
            return Result.error("这个人没有车队");
        }
        CaaQueueDtomap caaQueueDtomap=new CaaQueueDtomap();
        BeanUtils.copyProperties(one1,caaQueueDtomap);
        String address=one1.getStartpoint();
        //百度地图接口
        /*String URL = "https://api.map.baidu.com/geocoding/v3?";
        String body = HttpRequest.post(URL).form("ak", ak)
                .form("output", "json")
                .form("address",address).execute().body();


        String jsonData = body;
        JSONObject jsonObject = new JSONObject(jsonData);
        JSONObject locationObject = jsonObject.getJSONObject("result").getJSONObject("location");
        double lng = locationObject.getDouble("lng");
        double lat = locationObject.getDouble("lat");*/

        //修改处:高德地图接口
        //修改处：高德地图的接口
        double lng=0;
        double lat=0;
        try {
            String[] a= AmapUtils.getlocation(address);
            lng= Double.parseDouble(a[0]);
            lat= Double.parseDouble(a[1]);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        caaQueueDtomap.setLng(lng);
        caaQueueDtomap.setLat(lat);
        System.out.println("正在使用这个");
        List<CaaQueueDtomap> caaQueueDtomaps=new ArrayList<>();
        caaQueueDtomaps.add(caaQueueDtomap);
        return Result.success(caaQueueDtomaps);
    }

    @GetMapping("/allmap")
    @Transactional
    public Result<List<CaaQueueDtomap>> allmap() {
        List<CarQueue> list = carQueueService.list();

        List<CaaQueueDtomap> collect = list.stream().map(item -> {

            CaaQueueDtomap caaQueueDtomap = new CaaQueueDtomap();
            BeanUtils.copyProperties(item, caaQueueDtomap);
            String address = item.getStartpoint();
            //百度地图的地址编码接口
            /*String URL = "https://api.map.baidu.com/geocoding/v3?";
            String body = HttpRequest.post(URL).form("ak", ak)
                    .form("output", "json")
                    .form("address", address).execute().body();


            String jsonData = body;
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(jsonData);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            JSONObject locationObject = null;
            try {
                locationObject = jsonObject.getJSONObject("result").getJSONObject("location");
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            double lng = 0;
            try {
                lng = locationObject.getDouble("lng");
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            double lat = 0;
            try {
                lat = locationObject.getDouble("lat");
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }*/

            //修改处：高德地图的接口
            double lng=0;
            double lat=0;
            try {
                String[] a= AmapUtils.getlocation(address);
                lng= Double.parseDouble(a[0]);
                lat= Double.parseDouble(a[1]);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }

            caaQueueDtomap.setLng(lng);
            caaQueueDtomap.setLat(lat);
            return caaQueueDtomap;
        }).collect(Collectors.toList());

        return Result.success(collect);
    }

    @GetMapping("/carCtrl0")
    public Result<List<CarQueue>> re0(String username){
        LambdaQueryWrapper<User> userLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,username);
        User one = userService.getOne(userLambdaQueryWrapper);
        LambdaQueryWrapper<CarQueue> carQueueLambdaQueryWrapper=new LambdaQueryWrapper<>();
        carQueueLambdaQueryWrapper.eq(CarQueue::getInvitationcode,one.getInvitationcode());
        CarQueue one1 = carQueueService.getOne(carQueueLambdaQueryWrapper);
        List<CarQueue> carQueues=new ArrayList<>();
        carQueues.add(one1);
        return Result.success(carQueues);
    }

    @GetMapping("/carCtrl")
    public Result<List<CarQueue>> re1(){

        List<CarQueue> list = carQueueService.list();
        return Result.success(list);

    }

    @GetMapping("/show")
    public Result<List<User>> show1(String invitationcode)
    {
        LambdaQueryWrapper<User> userLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getInvitationcode,invitationcode);
        List<User> one = userService.list(userLambdaQueryWrapper);
        return Result.success(one);

    }




}
